<template>
  <div class='m-lesson_schedule'>
    <!-- 周期选择 -->
    <el-form :inline='true' label-width="100">
      <el-form-item label='上课时间：'>
        <el-date-picker
          v-model="selectParams.year"
          type="year"
          format='yyyy'
          @change='computingWeek'
          placeholder="选择上课时间">
        </el-date-picker>
      </el-form-item>
      <a-select
        v-model='selectParams.week'
        :options='weekOption'
        @change='updateSelectWeek'
      />
      <el-form-item>
        <el-button type='primary' @click='toCurrentWeek'>本周</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type='primary' @click='toNextWeek'>下周</el-button>
      </el-form-item>
    </el-form>
    <!-- 搜索 -->
    <el-form :inline='true' label-width="100">
      <el-form-item label='课程：'>
        <a-select
          v-model='search.lesson'
          :options='lessonData'
        />
      </el-form-item>
      <el-form-item label='教师：'>
        <a-select
          v-model='search.teacher'
          :options='teacherData'
        />
      </el-form-item>
      <el-form-item label='教室：'>
        <a-select
          v-model='search.classroom'
          :options='classroomData'
        />
      </el-form-item>
      <el-form-item label='班级：'>
        <a-select
          v-model='search.classes'
          :options='classesData'
        />
      </el-form-item>
      <el-form-item>
        <el-button type='primary'>搜索</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type='primary'>清空</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type='primary'>显示</el-button>
      </el-form-item>
    </el-form>
    <!-- table -->
    <schedule-table :weekData='weekTitleData' :data='formatData' />
  </div>
</template>

<script>
import { mapMutations } from 'vuex'
import moment from 'moment'
import scheduleTable from '@/module/lesson/components/scheduleTable'

const WEEK = {
  0: '一',
  1: '二',
  2: '三',
  3: '四',
  4: '五',
  5: '六',
  6: '日'
}

export default {
  name: 'm-lesson_schedule',

  components: {
    scheduleTable
  },

  data() {
    return {
      data: [],
      selectParams: {
        year: new Date(),
        week: -1
      },
      search: {
        lesson: '',
        teacher: '',
        classroom: '',
        classes: ''
      },
      currentMonthTheNumberWeek: 0,
      weekOption: [],
      weekTitleData: [], // 表格头部数据
      ifRequesting: false,
      classesTimeData: [],
      // 格式化后的数据
      formatData: [],
      // 下拉列表
      lessonData: [],
      teacherData: [],
      classroomData: [],
      classesData: []
    }
  },

  async mounted() {
    this.computingWeek()
    await this.getClassesTime()
    this.fetchData()
    // this.getLesson()
    // this.getTeacher()
    // this.getClassroom()
    // this.getClasses()
  },

  methods: {
    ...mapMutations(['setTabRoutes']),

    routerPush(type, args) {
      // push 到缓存里
      this.setTabRoutes({ type: 'add', obj: { ...this.getRouterInfoAccordingName(type), ...args } })
    },

    async fetchData(aPageNum, aPageSize) {
      const param = {
        aMerchantId: this.aFirmId,
        aPageNum,
        aPageSize
      }
      param.aBeginTime = this.computingCurrentDayForWeek(this.selectParams.week + 1, 'start')
      param.aEndTime = this.computingCurrentDayForWeek(this.selectParams.week + 1, 'end')
      const { code, data } = await this.$api.courseGetSchedules(param)
      if (code === 0) {
        this.formatDataFun(data.list)
      }
    },

    setTimeToFill(value) {
      if (value.length === 1) {
        return '0' + value
      }
      return value
    },

    async getClassesTime() {
      const { code, data } = await this.$api.courseGetClassTimes({
        aMerchantId: this.aFirmId
      })
      if (code === 0) {
        this.classesTimeData = data.list.map(v => {
          const desc = `${this.setTimeToFill(v.begin_hour)}:${this.setTimeToFill(v.begin_minute)} - ${this.setTimeToFill(v.end_hour)}:${this.setTimeToFill(v.end_minute)}`
          return {
            ...v,
            list: [{ type: 'template', desc }],
            desc
          }
        })
        for (let i = 0; i <= 6; i++) {
          this.classesTimeData.forEach(v => {
            v.list.push({
              desc: '暂无',
              weekly: i
            })
          })
        }
      }
    },

    formatDataFun(data) {
      this.formatData = []
      // 获取星期几
      data.forEach(v => {
        const obj = moment(new Date(parseInt(v.date + '000', 10)))
        v.date = parseInt(v.date, 10)
        v.weekly = obj.format('d')
      })
      this.classesTimeData.forEach(v => {
        data.some(item => {
          // 找到属于同一列的
          if (v.desc === item.time_name) {
            const teachers = item.teachers.map(v => v.name).join(',')
            // 根据 weekly 是第几个
            v.list[item.weekly] = {
              ...v,
              color: item.t10_schedule_fd_color,
              weekly: item.weekly,
              hasData: true,
              rearrangeable: item.rearrangeable,
              id: item.id,
              desc: `${item.course_name}（${item.room_name || ''}）（${teachers}}）（${item.class_name || ''}）`,
              list: []
            }
            return true
          }
          return false
        })
      })
      // 计算时间
      this.classesTimeData.forEach(list => {
        const timer = moment()
        timer.week(this.selectParams.week + 1)
        console.log(timer.week(), timer.month(), timer.date())
        list.list.forEach((item, index) => {
          if (index === 0) return
          timer.hour(list.begin_hour).minutes(list.begin_minute)
          item.dateStamp = parseInt(timer.format('x'), 10)
          timer.add(1, 'days')
        })
      })
      console.log(this.classesTimeData)
      this.formatData = JSON.parse(JSON.stringify(this.classesTimeData))
    },

    computingCurrentDayForWeek(week, type) {
      const obj = moment()
      obj.set('isoWeek', week)
      if (type === 'start') {
        obj.hours(0).minutes(0).seconds(0)
      } else {
        obj.date(obj.date() + 6).hours(23).minutes(59).seconds(59)
      }
      return obj.unix()
    },

    async toCurrentWeek() {
      const obj = moment()
      obj.set('isoWeek')
      // 设置回当前年份
      this.selectParams.year = new Date(parseInt(obj.format('x'), 10))
      this.computingWeek()
      await this.getClassesTime()
      this.fetchData()
    },

    async toNextWeek() {
      const obj = moment()
      obj.startOf('isoWeek')
      let week = obj.week()
      // 判断下周是否存在
      if (week > obj.isoWeek()) {
        // 不存在，自动加一年
        const year = obj.year() + 1
        obj.set('year', year)
        obj.set('isoWeek')
        this.selectParams.year = new Date(parseInt('' + obj.unix() + '000', 10))
        this.computingWeek()
        week = obj.week()
      } else {
        this.computingWeek(week)
      }
      this.selectParams.week = week
      await this.getClassesTime()
      this.fetchData()
    },

    computingWeek(week) {
      const arr = []
      const obj = moment()
      const nowYear = new Date(this.selectParams.year).getFullYear()
      obj.set('year', nowYear)
      obj.startOf('isoWeek')
      this.selectParams.week = week || obj.week() - 1
      this.setWeekTitleData()
      for (let i = 1; i < 53; i++) {
        obj.set('isoWeek', i)
        const week = obj.week()
        const startDate = obj.date()
        const startMonth = obj.month() + 1
        obj.set('date', startDate + 6)
        const endDate = obj.date()
        const endMonth = obj.month() + 1
        arr.push({
          week,
          startDate,
          endDate,
          startMonth,
          endMonth,
          value: i - 1,
          label: `第${week}周：${startMonth}.${startDate} - ${endMonth}.${endDate}`
        })
        obj.set('date', endDate - 6)
      }
      this.weekOption = arr
    },

    async updateSelectWeek() {
      console.log('update week', this.selectParams.week)
      this.setWeekTitleData()
      await this.getClassesTime()
      this.fetchData()
    },

    /**
     * 生成当前选择的周，是本月第几周
     * 且从几号到几号
     */
    setWeekTitleData() {
      const obj = moment()
      const tmp = []
      const { year, week } = this.selectParams
      console.log(week)
      obj.set('year', new Date(year).getFullYear())
      obj.set('isoWeek', week + 1)
      tmp[0] = {
        desc: `第${WEEK[Math.ceil(obj.date() / 7) - 1]}周课程表`
      }
      for (let i = 0; i <= 6; i++) {
        obj.startOf('isoWeek')
        obj.add(i, 'days')
        tmp.push({
          desc: `星期${WEEK[i]}（${obj.format('MM.DD')}）`
        })
      }
      this.weekTitleData = tmp
    },

    async getLesson() {
      const { code, data } = await this.$api.courseGetMines({
        aMerchantId: this.aFirmId
      })
      if (code === 0) {
        this.lessonData = data.list.map(v => ({
          value: v.id,
          label: v.name
        }))
      }
    },

    async getTeacher() {
      const { code, data } = await this.$api.firmGetStaffs({
        aFirmId: this.aFirmId
      })
      if (code === 0) {
        this.teacherData = data.list.map(v => ({
          value: v.id,
          label: v.name
        }))
      }
    },

    async getClassroom() {
      const { code, data } = await this.$api.courseGetRooms({
        aMerchantId: this.aFirmId
      })
      if (code === 0) {
        this.classroomData = data.list.map(v => ({
          value: v.id,
          label: v.name
        }))
      }
    },

    async getClasses() {
      const { code, data } = await this.$api.courseGetClasses({
        aMerchantId: this.aFirmId
      })
      if (code === 0) {
        this.classesData = data.list.map(v => ({
          value: v.id,
          label: v.name
        }))
      }
    }
  }
}
</script>

<style lang='less'>

</style>